package com.roy.minimq.remoting.domain.nettyclient;

import com.roy.minimq.remoting.domain.entity.RemotingCommand;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author ：楼兰
 * @date ：Created in 2021/8/9
 * @description:
 **/
@ChannelHandler.Sharable
public class NettyClientHandler extends SimpleChannelInboundHandler<RemotingCommand> {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private NettyRemotingClient remotingClient;

    public NettyClientHandler(NettyRemotingClient remotingClient){
        this.remotingClient = remotingClient;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
//        RemotingCommand command = new RemotingCommand();
//        command.setCode(1);
//        String message = "channelActive: test message";
//        command.setMessageLength(message.getBytes().length);
//        command.setMessage(message);
//        ctx.writeAndFlush(command);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, RemotingCommand remotingCommand) throws Exception {
        logger.info("client received message : {}",remotingCommand);
        int commandId = remotingCommand.getCommandId();

        if(this.remotingClient.getResponseTable().containsKey(commandId)){
            //放入响应后，同步等待的请求就能够及时拿到响应结果。
            this.remotingClient.getResponseTable().get(commandId).putResponse(remotingCommand);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error("client handler exceptionCaught : {} ", cause);
        ctx.close();
    }
}
